package com.mp.approvalreq.util;

import com.plusmoney.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class ObjectUtils {

	private static final Logger logger = LoggerFactory.getLogger(ObjectUtils.class);

	public static void initInteger(Object obj) {
		try {
			Field[] fields = obj.getClass().getDeclaredFields();
			Map<String, Method> methodMap = getDeclaredMethodMap(obj);
			for (Field field : fields) {
				if (Integer.class.equals(field.getType())) {
					String name = field.getName();
					String suffix = name.substring(0, 1).toUpperCase() + name.substring(1);
					Method get = methodMap.get("get" + suffix);
					if (Utils.isNull(get)) {
						logger.info("字段{}未生成get方法！！！", name);
						continue;
					}
					Object invoke = get.invoke(obj);
					if (Utils.isNull(invoke)) {
						Method set = methodMap.get("set" + suffix);
						if (Utils.isNull(set)) {
							logger.info("字段{}未生成set方法！！！", name);
							continue;
						}
						set.invoke(obj, 0);
						logger.info("{}初始化成功", name);
					}
				}
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	private static Map<String, Method> getDeclaredMethodMap(Object obj) {
		Method[] methods = obj.getClass().getDeclaredMethods();
		return Arrays.stream(methods).collect(Collectors.toMap(Method::getName, method -> method, (a, b) -> b));
	}

}
